from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text
from sqlalchemy.orm import relationship
from datetime import datetime
from db.database import Base

class CompilationHistory(Base):
    """编译历史记录模型"""
    __tablename__ = "compilation_history"
    
    id = Column(Integer, primary_key=True, index=True)
    task_id = Column(String(64), unique=True, index=True, comment="编译任务ID")
    status = Column(String(20), comment="状态: pending, processing, success, failed")
    error_message = Column(Text, nullable=True, comment="错误信息")
    optimize_level = Column(Integer, comment="优化级别")
    python_version = Column(String(10), comment="Python版本")
    platform = Column(String(20), comment="目标平台")
    keep_source = Column(Boolean, default=False, comment="是否保留源文件")
    zip_output = Column(Boolean, default=False, comment="是否压缩输出")
    delete_temp = Column(Boolean, default=True, comment="是否删除临时文件")
    extra_args = Column(String(255), nullable=True, comment="额外编译参数")
    output_dir = Column(String(255), comment="输出目录")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    completed_at = Column(DateTime, nullable=True, comment="完成时间")
    
    # 关联的文件
    files = relationship("CompilationFile", back_populates="history", cascade="all, delete-orphan")

class CompilationFile(Base):
    """编译文件模型"""
    __tablename__ = "compilation_files"
    
    id = Column(Integer, primary_key=True, index=True)
    history_id = Column(Integer, ForeignKey("compilation_history.id"), comment="关联的历史记录ID")
    original_filename = Column(String(255), comment="原始文件名")
    original_filesize = Column(Integer, comment="原始文件大小")
    output_filename = Column(String(255), nullable=True, comment="输出文件名")
    output_filesize = Column(Integer, nullable=True, comment="输出文件大小")
    is_source = Column(Boolean, default=True, comment="是否为源文件")
    
    # 关联的历史记录
    history = relationship("CompilationHistory", back_populates="files")

class PlatformStats(Base):
    """平台统计模型"""
    __tablename__ = "platform_stats"
    
    id = Column(Integer, primary_key=True, index=True)
    platform = Column(String(20), unique=True, comment="平台名称")
    count = Column(Integer, default=0, comment="使用次数")
    
    @staticmethod
    def get_platforms():
        return ["linux", "windows", "macos"]
